<template>
  <n-form
    ref="formRef"
    :model="formValue"
    label-width="80"
    label-placement="left"
    :rules="rules"
  >
    <n-form-item label="文章名" class="input" path="title">
      <n-input v-model:value="formValue.title" />
    </n-form-item>
    <n-form-item label="作者">
      {{ formValue.author?.nickname }}
    </n-form-item>
    <n-form-item label="分类" class="category" path="category">
      <n-select v-model:value="formValue.category" :options="categoryList" />
    </n-form-item>
    <n-form-item label="标签" class="tags" path="tags">
      <n-select
        class="tags-select"
        v-model:value="formValue.tags"
        multiple
        :options="tagList"
      />
    </n-form-item>
    <n-form-item label="开启评论" class="isCommentOpen" path="isCommentOpen">
      <n-switch v-model:value="formValue.isCommentOpen" />
    </n-form-item>
    <n-form-item label="文章状态" class="status" path="status">
      <n-radio
        :checked="formValue.status === 'draft'"
        value="draft"
        name="草稿"
        @change="handleChange"
      >
        草稿
      </n-radio>
      <n-radio
        :checked="formValue.status === 'publish'"
        value="publish"
        name="发布"
        @change="handleChange"
      >
        发布
      </n-radio>
    </n-form-item>
    <n-form-item label="摘要">
      <n-input
        v-model:value="formValue.summary"
        type="textarea"
        placeholder="文章摘要"
      />
    </n-form-item>
    <n-form-item label="封面">
      <Upload v-model:fileUrl="formValue.coverUrl" />
    </n-form-item>

    <n-form-item>
      <div class="btn">
        <n-button @click="createFunc"> 保存 </n-button>
      </div>
    </n-form-item>
  </n-form>
</template>

<script setup lang="ts">
import { findAll as apiFindAllTags } from "../../api/tag";
import { findAll as apiFindAllCategories } from "~/api/category";
import {
  type updatePost,
  findByIdAdmin as apiPostFindOneById,
  updateOne as apiPostUpdateOne,
} from "~/api/post";
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  NSelect,
  NSwitch,
  NRadio,
  type FormInst,
  type SelectGroupOption,
  type SelectOption,
  type UploadFileInfo,
} from "naive-ui";
const props = defineProps({
  id: {
    type: String,
  },
});
const emit = defineEmits(["afterUpdate"]);
const formValue = ref<updatePost>({
  title: "csss",
  tags: [],
  category: null,
  isCommentOpen: true,
  coverUrl: "",
  status: "draft",
  author: null,
  summary: "",
});
const rules = {
  title: {
    pattern: /^.{3,50}$/,
    message: "文章名必填，长度大于3位小于50位",
    required: true,
    trigger: "blur",
  },
  tags: {
    required: true,
    message: "标签必选",
  },
  category: {
    required: true,
    message: "分类必选",
  },
};
const formRef = ref<FormInst | null>(null);
const createFunc = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (errors) naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    if (props.id) {
      await apiPostUpdateOne(props.id, formValue.value);
      emit("afterUpdate");
    }
  });
};
const tagList = ref<Array<SelectOption | SelectGroupOption>>([]);
const categoryList = ref<Array<SelectOption | SelectGroupOption>>([]);
const getcategories = async () => {
  const res = await apiFindAllCategories();
  res.data.forEach((category) => {
    categoryList.value.push({
      label: category.name,
      value: category.id,
    });
  });
};
const getTags = async () => {
  const res = await apiFindAllTags();
  res.data.forEach((tag) => {
    tagList.value.push({
      label: tag.name,
      value: tag.id,
    });
  });
};
const findPost = async (id: string) => {
  const res = await apiPostFindOneById(id);
  if (res) {
    formValue.value = {
      ...res.data,
      tags: res.data.tags.map((tag) => tag.id),
      category: res.data.category?.id,
    };
  }
};
const handleChange = (e: Event) => {
  formValue.value.status = (e.target as HTMLInputElement).value as
    | "draft"
    | "publish";
};
watchEffect(() => {});
onMounted(() => {
  if (props.id) findPost(props.id as string);
  getcategories();
  getTags();
});
</script>
<style scoped lang="scss">
.n-form {
  :deep(.n-tag) {
    --n-color: var(--n-color);
  }
}
.btn {
  flex: 1;
  display: flex;
  flex-direction: row-reverse;
}
</style>
